package controller;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;

import javax.swing.JFrame;

import model.interactionHandlerInitializer.InteractionHandlerInitializer;
import model.interactionhandler.InteractionContainer;
import view.InteractionOverlay;
import view.View;

public class InteractionController extends Controller {

	private InteractionOverlay io;
	private JFrame gw;
	private InteractionContainer ic;
	
	public InteractionController( InteractionOverlay io, JFrame gameWindow, InteractionContainer ic ) {
		this.io = io;
		this.gw = gameWindow;
		this.ic = ic;
		io.register( this );
		this.initiate();
	}

	private void initiate() {
		gw.addKeyListener( new KeyListener() {
			@Override
			public void keyPressed(KeyEvent arg0) {
			 	if( arg0.getKeyCode() == GameConfig.EXIT_INTERACTION ) {//escape interaction
			 		ic.clear();
			 		io.escapeInteractionScreen();
				}
			}
			@Override
			public void keyReleased(KeyEvent arg0) {}
			@Override
			public void keyTyped(KeyEvent arg0) {}
		});
	}
	
	@Override
	public void update(View v) {
		//update the mouse listeners in the interaction overlay
		List<InteractionHandlerInitializer> l = ic.getInteractions();
		if( l == null || l.size() < 1 ) { return ; }
		this.io.clearListeners();
		for( final InteractionHandlerInitializer i : l ) {
			this.io.addListener( i, new MouseListener() {
				@Override
				public void mouseClicked(MouseEvent arg0) {
			 		io.escapeInteractionScreen();
					i.handle();
				}
				@Override
				public void mouseEntered(MouseEvent arg0) {}
				@Override
				public void mouseExited(MouseEvent arg0) {}
				@Override
				public void mousePressed(MouseEvent arg0) {	}
				@Override
				public void mouseReleased(MouseEvent arg0) {}
			} );
		}
	}
	
}
